package app

import (
	// "encoding/json"
	// "fmt"
	"net/http"
	"time"
	// "os"

	"github.com/go-apibox/api"
	"github.com/go-apibox/apisession"
	_ "github.com/mattn/go-sqlite3"
	"xorm.io/xorm"
)

var (
	app *App
)

type App struct {
	API    *api.App
	engine *xorm.Engine
	logger *api.Logger

	adminUser *User
	config    *Config

	// debugFile *os.File
}

func NewApp(configPath string) (*App, error) {

	tmp, err := api.NewAppFromFile(configPath)
	if err != nil {
		return nil, err
	}

	app = &App{
		API:    tmp,
		logger: tmp.Logger,
	}

	if err := app.initConfig(); err != nil {
		app.logger.Error("init config failed:", err)
		return nil, err
	}

	if err := app.initDB(); err != nil {
		app.logger.Error("init db failed:", err)
		return app, err
	}
	go func() {
		for {
			time.Sleep(time.Minute)
			t := &TaskLog{
				Status:  TASK_STATUS_TIMEOUT,
				EndTime: time.Now().Unix(),
			}
			app.engine.Where("stop_time<?", t.EndTime).Cols("status", "end_time").Update(t)
		}
	}()

	if err := app.initAdmin(); err != nil {
		app.logger.Error("init admin failed:", err)
		return nil, err
	}

	app.initGroupProduct()

	app.API.RegisterModel(new(User))
	app.API.RegisterModel(new(DeviceGroup))
	app.API.RegisterModel(new(Device))
	app.API.RegisterModel(new(Task))
	app.API.RegisterModel(new(Product))
	app.API.RegisterModel(new(TaskConfig))
	app.API.RegisterModel(new(DeviceWithGroup))
	// app.API.RegisterModel(new(TaskWithGroup))
	app.API.RegisterModel(new(ProductWithGroup))

	app.API.RegisterModel(new(TaskLog))
	app.API.RegisterModel(new(TaskGroup))
	return app, nil
}

func (app *App) Run() error {

	app.API.Use(new(MyMiddleware))
	app.API.Use(apisession.NewSession(app.API))

	return app.API.Run(app.GetRouter())
}

type MyMiddleware struct {
}

func (s *MyMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
	// do some stuff before

	w.Header().Add("Access-Control-Allow-Origin", "*")
	next(w, r)
	// do some stuff after

}
